/**
 * Created by dmrj on 2016/5/3.
 */
define(['jquery', 'appLocalStorage', 'appConst', 'model/global', 'appMessageBox','business/project/projectConfig', 'jeditable/jquery.jeditable',
    'jquery-form/jquery-form.min'], function ($, appLocalStorage, appConst, global, msgBox, projectConfig) {
    var MAX_LENGTH = 100;
    var that;
    var components = {};
    var data = {
        cp_dataFill: new Array(),
        cc_dataFill: new Array(),
        psa_dataFill: new Array(),
        psa_addData: [],
        searchKey_pcreate_code: "ispc.search.project.code." + global.getUserId()
    };

    return {
        init: function () {
            that = this;
            data.psa_addData = [];
            components = {
                "form_project": $("#project-form"),
                "form_radio1": $("#radio-form1"),
                "form_radio2": $("#radio-form2"),
                "form_psa": $("#psa-form"),
                "input_code": $("#code"),
                "input_name": $("#name"),
                "input_description": $("#description"),
                "radio_default1": $(".default1"),
                "radio_default2": $(".default2"),
                "input_dcgroupvalue": $("#dcgroupvalue"),
                "input_ccgroupvalue": $("#ccgroupvalue"),
                "radio_customGroup1": $(".customGroup1"),
                "radio_customGroup2": $(".customGroup2"),
                "tbl_dt_cpw": $("#dt_cpw"),
                "tbl_dt_cc": $("#dt_cc"),
                "tbl_dt_col": $("#dt_col"),
                "btn_saveAll": $("#btn_saveAll"),
                "btn_attributeSubmit": $("#attributeSubmit"),
                "input_psaAdd": $("#val"),

                slt_createProject_grr_type: $('#slt_createProject_grr_type'),
                slt_createProject_grr_sigma: $('#slt_createProject_grr_sigma'),
                txt_createProject_grr_part: $("#txt_createProject_grr_part"),
                txt_createProject_grr_operator: $("#txt_createProject_grr_operator"),
                txt_createProject_grr_trial: $("#txt_createProject_grr_trial"),
                form_grr_creatSetting: $("#form_grr_creatSetting"),
                txt_createProject_grr_Excellent: $("#txt_createProject_grr_Excellent"),
                txt_createProject_grr_Adequate: $("#txt_createProject_grr_Adequate"),
                txt_createProject_grr_Marginal: $("#txt_createProject_grr_Marginal")
            };

            that.initValidateRule();
            that.formValidate();
            that.initEventClick();

            that.initCCWRData();
            that.initCPWRData();
            that.initPSAData();

            that.initGrrSetting();
        },

        formValidate: function () {
            components.form_project.validate({
                rules: {
                    code: {
                        required: true,
                        keyContainBlankCheck: true,
                        remote: {
                            type: "POST",
                            url: "project/isCode",
                            dataType: 'json',
                            data: {
                                projectCode: function () {
                                    return components.input_code.val().trim();
                                }
                            }
                        }
                    },
                    name: {
                        required: true,
                        keyContainBlankCheck: true,
                        remote: {
                            type: "POST",
                            url: "project/isName",
                            dataType: 'json',
                            data: {
                                projectName: function () {
                                    return components.input_name.val().trim();
                                }
                            }
                        }
                    }
                },
                messages: {
                    code: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('PROJECT_CODE')),
                        remote: $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", $.i18n.prop('PROJECT_CODE'))
                    },
                    name: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('PROJECT_NAME')),
                        remote: $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", $.i18n.prop('PROJECT_NAME'))
                    }
                },
                submitHandler: function (form) {

                    var distributionChartGroupingNumber, controlChartGroupingNumber;
                    if (!$("input[name='group_dc']").eq(0).attr("checked")) {
                        distributionChartGroupingNumber = components.input_dcgroupvalue.val().trim();
                    }
                    if (!$("input[name='cc_group']").eq(0).attr("checked")) {
                        controlChartGroupingNumber = components.input_ccgroupvalue.val().trim();
                    }

                    var obj = {
                        "distributionChartGroupingNumber": distributionChartGroupingNumber,
                        "controlChartGroupingNumber": controlChartGroupingNumber
                    };

                    var value = new Array();
                    value.push(parseFloat(components.txt_createProject_grr_part.val()));
                    value.push(parseFloat(components.txt_createProject_grr_operator.val()));
                    value.push(parseFloat(components.txt_createProject_grr_trial.val()));
                    

                    var ruleValue = new Array();
                    ruleValue.push(parseFloat(components.txt_createProject_grr_Excellent.val()));
                    ruleValue.push(parseFloat(components.txt_createProject_grr_Adequate.val()));
                    ruleValue.push(parseFloat(components.txt_createProject_grr_Marginal.val()));

                    var grrSettingObj = {
                        model: components.slt_createProject_grr_type.select2("val"),
                        sigma: components.slt_createProject_grr_sigma.select2("val"),
                        defaultModelValue:JSON.stringify(value),
                        rule: JSON.stringify(ruleValue)
                    };

                    var dataCC = [];
                    var dataCP = [];
                    var dataPSA = [];

                    var param = {
                        name: components.input_name.val().trim(),
                        code: components.input_code.val().trim(),
                        description: components.input_description.val().trim(),
                        statisticAnalysisParameterDto: obj,
                        ccwrList: dataCC,
                        cpwrList: dataCP,
                        psgrrDto: grrSettingObj
                    };

                    components.tbl_dt_cpw.DataTable().data().each(function (d) {
                        var obj = {
                            "indiceName": d.indiceName,
                            "excellentBoundaryValue": d.excellentBoundaryValue,
                            "goodBoundaryValue": d.goodBoundaryValue,
                            "acceptableBoundaryValue": d.acceptableBoundaryValue,
                            "rectificationBoundaryValue": d.rectificationBoundaryValue
                        };
                        dataCP.push(obj);
                    });

                    components.tbl_dt_cc.DataTable().data().each(function (d) {
                        var visible = d.isVisible;
                        if (d.isVisible == "NO" || d.isVisible == false) {
                            visible = false;
                        }
                        else {
                            visible = true;
                        }
                        var obj = {
                            "code": d.code,
                            "isVisible": visible,
                            "detailRule": d.detailRule,
                            "points": d.points,
                            "somePoints": d.somePoints,
                            "sigma": d.sigma
                        };
                        dataCC.push(obj);
                    });

                    var dataCO = [];
                    components.tbl_dt_col.DataTable().data().each(function (d) {
                        var obj = {
                            "name": d.name,
                            "value": d.value,
                            "isDefault": d.isDefault,
                            "isShow": d.isShow
                        };
                        dataCO.push(obj);
                    });
                    dataPSA = dataCO.concat(data.psa_addData);
                    var arr = new Array();
                    param.psaList = dataPSA;
                    arr.push(param);

                    var DCFlag = that.checkDCGroup();
                    var CCFlag = that.checkCCGroup();
                    var tableFlag = that.checkTableData();
                    var grrSetting = that.checkGrrSetting();
                    if (DCFlag && tableFlag && CCFlag && grrSetting) {
                        $.ajax({
                            url: "project/addProject",
                            type: 'POST',
                            dataType: "json",
                            contentType: "application/json",
                            data: JSON.stringify(arr),
                            success: function (dataSrc) {
                                if (dataSrc.code == 0) {
                                    //var errorTip = data.message != null ? $.i18n.prop(data.message, [$.i18n.prop('MENU_PROJECT')]) : $.i18n.prop('GLOBAL_CREATE_FAIL', $.i18n.prop('MENU_PROJECT'));
                                    msgBox.errorBox(dataSrc.message != null ? dataSrc.message : 'GLOBAL_CREATE_FAIL', 'MENU_PROJECT');
                                    return false;
                                }
                                var projectCode = components.input_code.val().trim();
                                var projectName = components.input_name.val().trim();

                                appLocalStorage.setLocal(data.searchKey_pcreate_code, projectCode);
                                window.location.href = "#project";
                            },
                            error: function (e) {
                                if (e.status == 401) {
                                    msgBox.sessionFailureBox();
                                }
                                if (e.status == 500) {
                                    msgBox.serverFailureBox();
                                }
                                if (e.status == 404) {
                                    msgBox.pathFailureBox();
                                }
                            }
                        });
                    }
                    else if (!tableFlag) {
                        msgBox.show({
                            content: $.i18n.prop("GLOBAL_TABLE_LANG_ZERORECORDS"),
                            type: "warning"
                        });
                    }
                },

                errorPlacement: function (error, element) {
                    error.insertAfter(element.parent());
                }
            });
        },

        checkPsaAttribute: function () {
            var $validator = components.form_psa.validate({
                rules: {
                    val: {
                        required: true,
                        keyContainBlankCheck: true
                    }
                },
                messages: {
                    val: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('ATTRIBUTE_PROJECT_ATTRIBUTE'))
                    }
                }
            });

            var $valid = components.form_psa.valid();
            if (!$valid) {
                $validator.focusInvalid();
                return false;
            }
            return true;
        },
        checkDCGroup: function () {
            if (!$("input[name='group_dc']").eq(0).prop("checked")) {
                var $validator = components.form_radio1.validate({
                    rules: {
                        analysisName: {
                            required: true,
                            positiveinteger: true
                        }
                    },
                    messages: {
                        analysisName: {
                            required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('PROJECT_GROUP_NUMBER')),
                        }
                    }
                });

                var $valid = components.form_radio1.valid();
                if (!$valid) {
                    $validator.focusInvalid();
                    return false;
                }
            }
            return true;
        },
        checkCCGroup: function () {
            if (!$("input[name='cc_group']").eq(0).prop("checked")) {
                var $validator1 = components.form_radio2.validate({
                    rules: {
                        analysisNameCC: {
                            required: true,
                            positiveinteger: true
                        }
                    },
                    messages: {
                        analysisNameCC: {
                            required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('PROJECT_GROUP_NUMBER')),
                        }
                    }
                });
                var $valid1 = components.form_radio2.valid();
                if (!$valid1) {
                    $validator1.focusInvalid();
                    return false;
                }
            }
            return true;
        },
        checkTableData: function () {
            if ($("td").hasClass("tableDataError")) {
                return false;
            }

            else {
                return true;
            }
        },
        checkGrrSetting: function () {
            var excellentValue = components.txt_createProject_grr_Excellent.val();
            var adequateValue = components.txt_createProject_grr_Adequate.val();
            var marginalValue = components.txt_createProject_grr_Marginal.val();

            var adequateParam = {
                beforeValue: excellentValue,
                afterValue: marginalValue
            };

            var $validator = components.form_grr_creatSetting.validate({
                rules: {
                    appraisers: {
                        required: true,
                        positiveinteger: true
                    },
                    trials: {
                        required: true,
                        positiveinteger: true
                    },
                    parts: {
                        required: true,
                        positiveinteger: true
                    },
                    excellent: {
                        required: true,
                        positiveinteger: true,
                        excellentRule: adequateValue
                    },
                    adequate: {
                        required: true,
                        positiveinteger: true,
                        betweenRule: adequateParam
                    },
                    marginal: {
                        required: true,
                        positiveinteger: true,
                        marginalRule: adequateValue
                    }
                },
                messages: {
                    appraisers: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', "appraisers"),
                    },
                    trials: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', "trials"),
                    },
                    parts: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', "parts"),
                    },
                    excellent: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', "excellent"),
                    },
                    adequate: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', "adequate"),
                    },
                    marginal: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', "marginal"),
                    }
                }
            });

            $validator.settings.rules.excellent.excellentRule = adequateValue;
            $validator.settings.rules.adequate.betweenRule = adequateParam;
            $validator.settings.rules.marginal.marginalRule = adequateValue;

            var $valid = components.form_grr_creatSetting.valid();
            if (!$valid) {
                $validator.focusInvalid();
                return false;
            }
            else {
                return true;
            }
        },

        initValidateRule: function () {
            projectConfig.positiveInt();
            projectConfig.excellentRuleCheck();
            projectConfig.betweenRuleCheck();
            projectConfig.marginalRuleCheck();
        },
        initEventClick: function () {

            components.input_ccgroupvalue.attr("disabled", "disabled");
            components.input_dcgroupvalue.attr("disabled", "disabled");

            components.radio_default1.click(function () {
                components.input_dcgroupvalue.val("");
                components.input_dcgroupvalue.attr("disabled", "disabled");

                if (components.input_dcgroupvalue.parent().hasClass("state-error")) {

                    components.input_dcgroupvalue.parent().removeClass("state-error");
                    components.input_dcgroupvalue.next().remove();
                }

                components.input_dcgroupvalue.parent().removeClass("state-success");
            });

            components.radio_default2.click(function () {
                components.input_ccgroupvalue.val("");
                components.input_ccgroupvalue.attr("disabled", "disabled");

                if (components.input_ccgroupvalue.parent().hasClass("state-error")) {

                    components.input_ccgroupvalue.parent().removeClass("state-error");
                    components.input_ccgroupvalue.next().remove();
                }
                components.input_ccgroupvalue.parent().removeClass("state-error");
                components.input_ccgroupvalue.parent().removeClass("state-success");
            });

            components.radio_customGroup2.click(function () {
                components.input_ccgroupvalue.removeAttrs("disabled");
                components.input_ccgroupvalue.focus();
            });

            components.radio_customGroup1.click(function () {
                components.input_dcgroupvalue.removeAttrs("disabled");
                components.input_dcgroupvalue.focus();
            });

            $(':radio[name=group_dc]').each(function () {
                $(this).click(function () {
                    $(':radio[name=group_dc]').removeAttr('checked');
                    $(this).prop('checked', "checked");
                });
            });

            $(':radio[name=cc_group]').each(function () {
                $(this).click(function () {
                    $(':radio[name=cc_group]').removeAttr('checked');
                    $(this).prop('checked', "checked");
                });
            });

            $(components.btn_attributeSubmit).click(function () {
                if (that.checkPsaAttribute()) {
                    that.add();
                }
            });

            components.input_psaAdd.click(function () {
                that.clearContent();
            });
        },
        initCPWRData: function () {
            $.ajax({
                url: "project/findCPWR",
                type: 'POST',
                success: function (d) {
                    if (d.code != 0) {
                        data.cp_dataFill = d.body;
                        that.initCPWRTable();
                    } else {
                        //var errorTip = d.message != null ? $.i18n.prop(d.message, [$.i18n.prop('MENU_SYSTEM_ALARMRULE')]) : $.i18n.prop('GLOBAL_SEARCH_FAIL', $.i18n.prop('MENU_SYSTEM_ALARMRULE'));

                        msgBox.errorBox(d.message != null ? d.message : 'GLOBAL_SEARCH_FAIL', 'MENU_SYSTEM_ALARMRULE');
                        return false;
                    }
                },
                error: function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        initCPWRTable: function () {
            components.tbl_dt_cpw.DataTable({
                "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'><'col-sm-6 col-xs-12 hidden-xs'>r>" +
                "t" +
                "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "paging": false,
                "autoWidth": false,
                "ordering": false,
                "language": appConst.table_language(),
                "data": data.cp_dataFill,
                "columns": [
                    {"data": "indiceName"},
                    {"data": "excellentBoundaryValue"},
                    {"data": "goodBoundaryValue"},
                    {"data": "acceptableBoundaryValue"},
                    {"data": "rectificationBoundaryValue"}
                ],
                "columnDefs": [
                    {
                        "targets": [0],
                        "render": function (data, type, full) {
                            if (data == 'CA') {
                                return data + " (%)"
                            }
                            return data;
                        }
                    },
                    {
                        "targets": [1],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'excellentBoundaryValue').attr('dataId', row);
                        }
                    }, {
                        "targets": [2],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'goodBoundaryValue').attr('dataId', row);
                        }
                    }, {
                        "targets": [3],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'acceptableBoundaryValue').attr('dataId', row);
                        }
                    }, {
                        "targets": [4],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('type', 'rectificationBoundaryValue').attr('dataId', row);
                        }
                    }],
                "drawCallback": function (settings) {
                    var api = this.api();
                    $('#dt_cpw tbody td.inputTd').jeditable(function (value, settings) {
                        var cell = api.cell(this);
                        var cpw = document.getElementById('dt_cpw');
                        cell.data(value);

                        var r = parseInt($(this).attr('dataId')) + 1;
                        var name = $(this).attr('type');
                        var value = value;

                        var tel = /^[a-zA-Z0-9.]+$/;
                        if (isNaN(value) == true || !tel.test(value)) {
                            value = "";
                        }

                        if (value.length > MAX_LENGTH) {
                            $(this).addClass("tableDataError");
                            settings.placeholder = $.i18n.prop("MESSAGE_VALIDATE_LENGTH", $.i18n.prop("GLOBAL_FIELD_MAX"));
                            return false;
                        } else {
                            $(this).removeClass("tableDataError");
                        }

                        if (value == "") {
                            $(this).addClass("tableDataError");
                            settings.placeholder = $.i18n.prop("VALIDATE_CCW");
                            return false;
                        } else {
                            $(this).removeClass("tableDataError");
                        }
                        if (name == 'excellentBoundaryValue') {
                            var value1 = cpw.rows[r].cells[2].innerHTML;
                            if (r == 1 && parseFloat(value) > parseFloat(value1)) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_NEXT");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                            if (r != 1 && parseFloat(value) < parseFloat(value1)) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_NEXT");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                        }

                        if (name == 'goodBoundaryValue') {
                            var value1 = cpw.rows[r].cells[3].innerHTML;
                            var value2 = cpw.rows[r].cells[1].innerHTML;
                            if (r == 1 && (parseFloat(value) > parseFloat(value1))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_NEXT");
                                return false;
                            } else if (r == 1 && (parseFloat(value) < parseFloat(value2))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_PREVIOUS");
                                return false;
                            }
                            else {
                                $(this).removeClass("tableDataError");
                            }
                            if (r != 1 && (parseFloat(value) < parseFloat(value1))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_PREVIOUS");
                                return false;
                            } else if (r != 1 && (parseFloat(value) > parseFloat(value2))) {
                                $(this).attr("style", "background: #fff0f0;font-size:12px;color: #D56161");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_NEXT");
                                return false;
                            }
                            else {
                                $(this).removeClass("tableDataError");
                            }
                        }

                        if (name == 'acceptableBoundaryValue') {
                            var value1 = cpw.rows[r].cells[4].innerHTML;
                            var value2 = cpw.rows[r].cells[2].innerHTML;
                            if (r == 1 && (parseFloat(value) > parseFloat(value1))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_PREVIOUS");
                                return false;
                            } else if (r == 1 && (parseFloat(value) < parseFloat(value2))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_NEXT");
                                return false;
                            }
                            else {
                                $(this).removeClass("tableDataError");
                            }
                            if (r != 1 && (parseFloat(value) < parseFloat(value1))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_PREVIOUS");
                                return false;
                            } else if (r != 1 && (parseFloat(value) > parseFloat(value2))) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_NEXT");
                                return false;
                            }
                            else {
                                $(this).removeClass("tableDataError");
                            }
                        }

                        if (name == 'rectificationBoundaryValue') {
                            var value1 = cpw.rows[r].cells[3].innerHTML;
                            if (r == 1 && parseFloat(value) < parseFloat(value1)) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_GTE_PREVIOUS");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                            if (r != 1 && parseFloat(value) > parseFloat(value1)) {
                                $(this).addClass("tableDataError");
                                settings.placeholder = $.i18n.prop("VALIDATE_CCW_LTE_PREVIOUS");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                        }
                    }, {
                        height: '20',
                        width: '200',
                        cssclass: 'smart-form'
                    });
                }
            });
        },
        initCCWRData: function () {
            $.ajax({
                url: "project/findCCWR",
                type: 'POST',
                success: function (d) {
                    if (d.code != 0) {
                        data.cc_dataFill = d.body;
                        that.initCCWRTable();
                    } else {
                        //var errorTip = d.message != null ? $.i18n.prop(d.message, [$.i18n.prop('MENU_SYSTEM_ALARMRULE')]) : $.i18n.prop('GLOBAL_SEARCH_FAIL', $.i18n.prop('MENU_SYSTEM_ALARMRULE'));
                        msgBox.errorBox(d.message != null ? d.message : 'GLOBAL_SEARCH_FAIL', 'MENU_SYSTEM_ALARMRULE');
                        return false;
                    }
                },
                error: function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        initCCWRTable: function () {
            components.tbl_dt_cc.DataTable({
                "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'><'col-sm-6 col-xs-12 hidden-xs'>r>" +
                "t" +
                "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "paging": false,
                "autoWidth": false,
                "ordering": false,
                "language": appConst.table_language(),
                "data": data.cc_dataFill,
                "columns": [
                    {"data": "code"},
                    {"data": "isVisible"},
                    {"data": "detailRule"},
                    {"data": "points"},
                    {"data": "somePoints"},
                    {"data": "sigma"}
                ],
                "columnDefs": [
                    {
                        "targets": [1],
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = 'YES';
                            } else if (data == false) {
                                result = 'NO';
                            }
                            return result;
                        },
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('selctTd').attr('data-code', 'td_isVisible');
                        }
                    }, {
                        "targets": [3],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('data-code', 'td_points');
                        }
                    }, {
                        "targets": [4],
                        "render": function (data, type, full) {
                            var result = "";
                            if (full.code == "R5" || full.code == "R6") {
                                result = data;
                            } else {
                                result = "--";
                            }
                            return result;
                        },
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('data-code', 'td_somePoints');
                            if (row != 4 && row != 5) {
                                $(td).removeClass('inputTd');
                                $(td).attr('style', 'color:#C0C0C0');
                            }
                        }
                    }, {
                        "targets": [5],
                        "render": function (data, type, full) {
                            var result = "";
                            if (full.code == "R2" || full.code == "R3" || full.code == "R4") {
                                result = "--";
                            } else {
                                result = data;
                            }
                            return result;
                        },
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('data-code', 'td_sigma');
                            if (row > 0 && row < 4) {
                                $(td).removeClass('inputTd');
                                $(td).attr('style', 'color:#C0C0C0');
                            }
                        }
                    }],
                "drawCallback": function (settings) {
                    var api = this.api();
                    $('#dt_cc tbody td.inputTd').jeditable(function (value, settings) {
                        var cell = api.cell(this);
                        cell.data(value);

                        var tel = /^[a-zA-Z0-9.]+$/;
                        if (isNaN(value) == true || !tel.test(value)) {
                            value = "";
                        }

                        if (value.length > MAX_LENGTH) {
                            $(this).addClass("tableDataError");
                            settings.placeholder = $.i18n.prop("MESSAGE_VALIDATE_LENGTH", $.i18n.prop("GLOBAL_FIELD_MAX"));
                            return false;
                        } else {
                            $(this).removeClass("tableDataError");
                        }

                        if (value == "") {
                            $(this).addClass("tableDataError");
                            settings.placeholder = $.i18n.prop("VALIDATE_CCW");
                            return false;
                        } else {
                            $(this).removeClass("tableDataError");
                        }
                        var code = $(this).attr('data-code') + '_' + cell.data();
                        $(this).attr('data-code', code);
                    }, {
                        height: '20',
                        width: '100',
                        //onblur:'ignore',
                        cssclass: 'smart-form',
                        placeholder: $.i18n.prop("VALIDATE_CCW")
                    });
                    $('#dt_cc tbody td.selctTd').jeditable(function (value, settings) {
                            var cell = api.cell(this);
                            cell.data(value);
                            $(this).html(cell.data());
                        }, {
                            type: 'select',
                            submit: $.i18n.prop('GLOBAL_BUTTON_OK'),
                            data: {"YES": "YES", "NO": "NO"}
                        }
                    );
                }
            });
        },
        initPSAData: function () {
            $.ajax({
                url: "project/findPSA",
                type: 'POST',
                success: function (d) {
                    if (d.code != 0) {
                        data.psa_dataFill = d.body;
                        that.initPSATable();
                    } else {
                        //var errorTip = d.message != null ? $.i18n.prop(d.message, [$.i18n.prop('PROJECT_COLUMN')]) : $.i18n.prop('PROJECT_COLUMN', $.i18n.prop('MENU_SYSTEM_ALARMRULE'));
                        msgBox.errorBox(d.message, 'PROJECT_COLUMN');
                        return false;
                    }
                },
                error: function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        initPSATable: function () {
            components.tbl_dt_col.DataTable({
                "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'><'col-sm-6 col-xs-12 hidden-xs'>r>" +
                "t" +
                "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "paging": false,
                "autoWidth": false,
                "ordering": false,
                "language": appConst.table_language(),
                "data": data.psa_dataFill,
                "columns": [
                    {"data": "name"},
                    {"data": "value"},
                    {"data": "isDefault"},
                    {"data": "isDefault"},
                    {"data": "isShow"}
                ],
                "columnDefs": [
                    {
                        "targets": [1],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('data-code', 'value');
                        }

                    },
                    {
                        "targets": [2],
                        "visible": false,
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = 'YES';
                            } else if (data == false) {
                                result = 'NO';
                            }
                            return result;
                        }
                    },
                    {
                        "targets": [3],
                        "render": function (data, type, full) {
                            var operate = '';
                            return operate;
                        }
                    }],

                "drawCallback": function (settings) {
                    var api = this.api();
                    $('#dt_col tbody td.inputTd').jeditable(function (value, settings) {
                        var cell = api.cell(this);
                        value = $.trim(value);
                        cell.data(value);
                        var column = document.getElementById('dt_col');
                        var line = column.rows.length;
                        var count = 0;
                        for (var j = 1; j < line; j++) {
                            var cells1 = column.rows[j].cells[1].innerHTML;
                            if ($.trim(value) == $.trim(cells1)) {
                                count++;
                                if (count > 1) {
                                    var a = false;
                                    break;
                                }
                            } else
                                var a = true;
                        }

                        if (a == false) {
                            cell.data(cell.data());
                            $(this).addClass("tableDataError");
                            return false;
                        } else {
                            if (value == "") {
                                $(this).addClass("tableDataError");
                                return false;
                            } else {
                                $(this).removeClass("tableDataError");
                            }
                        }
                        var code = $(this).attr('data-code') + '_' + cell.data();
                        $(this).attr('data-code', code);
                    }, {
                        height: '20',
                        width: '300',
                        cssclass: 'smart-form',
                        placeholder: $.i18n.prop("VALIDATE_ATTRIBUTE")
                    });
                }
            });
        },
        initGrrSetting:function () {
            components.slt_createProject_grr_type.select2({
                id: function (rs) {
                    return rs.id;
                },
                // allowClear: true,
                data: function () {
                    return {
                        results: [{id: "NORMAL", text: "Appraisers - Trial - Part"},
                            {id: "SLOT", text: "Slot - Trial - Part"}]
                    };
                },
                formatResult: function (d) {
                    var itemFmt = "<span>" + d.text == null ? '' : d.text + "</span>";
                    return itemFmt;
                },
                formatSelection: function (d) {
                    return d.text == null ? '' : d.text;
                },
                formatMatches: function () {
                },
                formatNoMatches: function () {
                    return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                },
                escapeMarkup: function (m) {
                    return m;
                }
            });
            components.slt_createProject_grr_type.select2('val', 'NORMAL');

            components.slt_createProject_grr_sigma.select2({
                id: function (rs) {
                    return rs.id;
                },
                // allowClear: true,
                data: function () {
                    return {
                        results: [{id: "6.0", text: "6.0"},
                            {id: "5.15", text: "5.15"}]
                    };
                },
                formatResult: function (d) {
                    var itemFmt = "<span>" + d.text == null ? '' : d.text + "</span>";
                    return itemFmt;
                },
                formatSelection: function (d) {
                    return d.text == null ? '' : d.text;
                },
                formatMatches: function () {
                },
                formatNoMatches: function () {
                    return $.i18n.prop("GLOBAL_SELECTOR_NORESULT");
                },
                escapeMarkup: function (m) {
                    return m;
                }
            });
            components.slt_createProject_grr_sigma.select2('val', '6.0');
        },

        add: function () {
            var column = document.getElementById('dt_col');
            var val = document.getElementById("val").value;
            var line = column.rows.length;
            var a;
            for (var j = 1; j < line; j++) {
                var cells0 = column.rows[j].cells[0].innerHTML;
                var cells1 = column.rows[j].cells[1].innerHTML;
                if ($.trim(val) == $.trim(cells1)) {
                    a = false;
                    break;
                }
                else {
                    if ($.trim(val) == $.trim(cells0)) {
                        a = false;
                        break;
                    } else
                        a = true;
                }
            }

            if (a == true) {
                components.input_psaAdd.parent().removeClass("state-error");
                components.input_psaAdd.parent().addClass("state-success");
                var name = $.trim(val);
                var def = "false";
                var no;
                var x = column.insertRow(line);
                if (def == "false") {
                    no = "NO";
                }
                var enter = new Array();
                for (var i = 0; i < 4; i++) {
                    enter [i] = x.insertCell(i);
                }
                enter[0].innerHTML = name;
                enter[1].innerHTML = $.trim(val);
                enter[2].innerHTML = "<a href='javascript:;' class='deleteCreatePSA' id='" + val + "' >" + $.i18n.prop("GLOBAL_DELETE") + "</a>";
                enter[3].innerHTML = '<input type="checkbox" id="checkbox" name="checkbox' + line + '" checked="checked"/>';
                var show = $("input[name=checkbox" + line + "]").is(':checked');
                $("input[name=checkbox" + line + "]:checkbox").click(function () {
                    if ($(this).is(':checked')) {
                        show = true;
                    } else {
                        show = false;
                    }
                    (data.psa_addData)[line - 8].isShow = show;
                });

                var obj = {
                    "name": name,
                    "value": $.trim(val),
                    "isDefault": def,
                    "isShow": show
                };
                data.psa_addData.push(obj);
                components.tbl_dt_col.find(".deleteCreatePSA").unbind('click').on('click', function (obj) {
                    that.del($(this).attr("id"));
                });

            } else {
                components.input_psaAdd.parent().removeClass("state-success");
                components.input_psaAdd.parent().addClass("state-error");
                document.getElementById("add-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", $.i18n.prop('PROJECT_COLUMN')) + "</font>";
                return false;
            }
        },
        del: function (val) {
            components.tbl_dt_col.find('a[id=' + val + ']').parent().parent().remove();
            for (var i = 0; i < data.psa_addData.length; i++) {

                if (data.psa_addData[i].name == val) {
                    data.psa_addData.splice(i, 1);
                }
            }
        },
        clearContent: function () {
            components.input_psaAdd.val("");
        }
    }
});